package com.example.xianji.activity;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

/***************************百科创建词条****************************************/
public class Main_BaiKe_SetActivity extends Activity implements OnClickListener {
    private RelativeLayout bianji_citiao_back;
    private Button baike_citiao_submit, baike_get_phone_code;
    private EditText baike_edittext_telephone, baike_edittext_tuxing_code, baike_edittext_phone_code, baike_set_citiao_name, baike_edittext_username;
    private Drawable d;
    private ImageView baike_set_citiao_image_tuxing;
    private TimeCount mTimeCount;
    private ProgressDialog pd;
    private String phone;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                baike_set_citiao_image_tuxing.setImageDrawable(d);
            }
        }
    };

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__bai_ke__set);
        bianji_citiao_back = (RelativeLayout) findViewById(R.id.bianji_citiao_back);
        baike_citiao_submit = (Button) findViewById(R.id.baike_citiao_submit);
        baike_edittext_telephone = (EditText) findViewById(R.id.baike_edittext_telephone);
        baike_set_citiao_image_tuxing = (ImageView) findViewById(R.id.baike_set_citiao_image_tuxing);
        baike_get_phone_code = (Button) findViewById(R.id.baike_get_phone_code);
        baike_edittext_tuxing_code = (EditText) findViewById(R.id.baike_edittext_tuxing_code);
        baike_edittext_phone_code = (EditText) findViewById(R.id.baike_edittext_phone_code);
        baike_set_citiao_name = (EditText) findViewById(R.id.baike_set_citiao_name);
        baike_edittext_username = (EditText) findViewById(R.id.baike_edittext_username);

        mTimeCount = new TimeCount(60000, 1000);
        pd = new ProgressDialog(this);
        bianji_citiao_back.setOnClickListener(this);
        baike_citiao_submit.setOnClickListener(this);
        baike_get_phone_code.setOnClickListener(this);
        baike_set_citiao_image_tuxing.setOnClickListener(this);
        baike_edittext_telephone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    phone = s.toString();
                    final String url = Contant.tuxing_yanzheng + s.toString();
                    XJApplication.cachThreadPool.execute(new Runnable() {

                        @Override
                        public void run() {
                            LoadImageFromWebOperations(url);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bianji_citiao_back) {
            Main_BaiKe_SetActivity.this.finish();
        } else if (v.getId() == R.id.baike_citiao_submit) {
            //词条提交
            pd.show();
            if (baike_edittext_username.getText().toString().length() > 0) {
                if (baike_set_citiao_name.getText().toString().length() > 0) {
                    set_citiao_data();
                } else {
                    Toast.makeText(Main_BaiKe_SetActivity.this, "请输入词条名称", 0).show();
                }
            } else {
                Toast.makeText(Main_BaiKe_SetActivity.this, "请输入姓名", 0).show();
            }

        } else if (v.getId() == R.id.baike_get_phone_code) {
            //获取手机验证短信
            if (baike_edittext_telephone.getText().toString().length() == 11) {
                if (baike_edittext_tuxing_code.getText().toString().length() > 0) {
                    huoqu_yanzhengma();
                } else {
                    Toast.makeText(Main_BaiKe_SetActivity.this, "请输入正确的图形验证码", 0).show();
                }
            } else {
                Toast.makeText(Main_BaiKe_SetActivity.this, "请输入正确手机号", 0).show();
            }

        } else if (v.getId() == R.id.baike_set_citiao_image_tuxing) {
            final String phone_url = Contant.tuxing_yanzheng + phone;
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    LoadImageFromWebOperations(phone_url);
                }
            });
        }
    }

    /********************创建词条数据****************************************************/
    public void set_citiao_data() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("picverify", baike_edittext_tuxing_code.getText().toString());//图片验证码
        parms.addBodyParameter("wname", baike_set_citiao_name.getText().toString());//创建的词条
        parms.addBodyParameter("uname", baike_edittext_username.getText().toString());//用户姓名
        parms.addBodyParameter("mobverify", baike_edittext_phone_code.getText().toString());//手机验证码
        parms.addBodyParameter("umobile", baike_edittext_telephone.getText().toString());//手机号
        httpUtils.send(HttpMethod.POST, Contant.submit_citiao, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_BaiKe_SetActivity.this, obj.getString("msg"), 0).show();
                    if (obj.getInt("status") == 1) {
                        pd.cancel();
                        Main_BaiKe_SetActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取短信验证
     */
    public void huoqu_yanzhengma() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        //	parms.addBodyParameter("code_from","");
        parms.addBodyParameter("mobile", baike_edittext_telephone.getText().toString());
        parms.addBodyParameter("picverify", baike_edittext_tuxing_code.getText().toString());

        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_BaiKe_SetActivity.this, obj.getString("msg"), 0).show();
                    if (obj.getString("msg").equals("提交成功")) {
                        mTimeCount.start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 通过URL加载ImageView
     *
     * @param url
     * @return
     */
    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            d = Drawable.createFromStream(is, "src name");
            handler.sendEmptyMessage(1);
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    /***********************倒计时*******************************************/
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// ��������Ϊ��ʱ��,�ͼ�ʱ��ʱ����
        }

        @Override
        public void onFinish() {
            baike_get_phone_code.setText("重新获取");
            baike_get_phone_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_style));
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                baike_get_phone_code.setText("60秒");
            }
            baike_get_phone_code.setText(str + "秒");
            baike_get_phone_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.regiseter_huise_style));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
